package com.lidx.back.statistics.dao.impl;

import java.util.Collections;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;


import com.google.common.collect.Collections2;
import com.lidx.back.statistics.dao.ISystemVersionDao;
import com.lidx.back.statistics.entity.SystemVersionConfig;
import com.lidx.back.statistics.rest.VersionBean;
@Repository
public class SystemVersionDaoImpl implements ISystemVersionDao {

	@Autowired
	private SessionFactory sessionFactory;
	
	public SystemVersionConfig getConfig(VersionBean versionBean) {
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery("from SystemVersionConfig where versionType=:vType and versionNum = :vNum")
				.setString("vType", versionBean.getVersionType())
				.setString("vNum", versionBean.getVersionNumber());
		List list = query.list();
		if(list.size()>0)
			return (SystemVersionConfig) list.get(0);
		return null;
	}

	public String getLatestVersionNum(String versionType) {
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery("select distinct latestVersionNum from SystemVersionConfig where versionType=:vType")
				.setString("vType", versionType);
		return (String) query.uniqueResult();
	}

	public List<SystemVersionConfig> getVersionList(VersionBean versionBean) {
		Session session = sessionFactory.getCurrentSession();
		StringBuffer sb = new StringBuffer("from SystemVersionConfig where 1 = 1");
		if(StringUtils.isNotBlank(versionBean.getVersionType())){
			sb.append(" and versionType = '").append(versionBean.getVersionType()).append("'");
		}
		if(StringUtils.isNotBlank(versionBean.getVersionNumber())){
			sb.append(" and versionNum = '").append(versionBean.getVersionNumber()).append("'");
		}
		Query query = session.createQuery(sb.toString());
		List list = query.list();
		if(list.size()>0)
			return list;
		return null;
	}

	public void save(SystemVersionConfig versionConfig) {
		Session session = sessionFactory.getCurrentSession();
		session.save(versionConfig);
		session.flush();
	}

	public List<String> getVersionNumbers() {
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createSQLQuery("select distinct versionNum from system_version");
		List list = query.list();
		if(!list.isEmpty()){
			return list;
		}
		return null;
	}

}
